import anime from "animejs";
import Particles from "./particles";

export default function() {
  const particlesOpts = {
    duration: 500,
    easing: "easeOutQuad",
    speed: 0.1,
    particlesAmountCoefficient: 10,
    oscillationCoefficient: 80
  };

  const items = document.querySelectorAll(".grid__item");
  items.forEach(el => {
    const bttn = el.querySelector("button.particles-button");
    const bttnBack = el.querySelector("button.action");

    let buttonVisible = true;

    particlesOpts.complete = () => {
      if (!buttonVisible) {
        anime.remove(bttnBack);
        anime({
          targets: bttnBack,
          duration: 300,
          easing: "easeOutQuint",
          opacity: 1,
          scale: [0, 1]
        });
        bttnBack.style.pointerEvents = "auto";
      }
    };
    const particles = new Particles(bttn, particlesOpts);

    bttn.addEventListener("click", () => {
      if (!particles.isAnimating() && buttonVisible) {
        particles.disintegrate();
        buttonVisible = !buttonVisible;
      }
    });
    bttnBack.addEventListener("click", () => {
      if (!particles.isAnimating() && !buttonVisible) {
        anime.remove(bttnBack);
        anime({
          targets: bttnBack,
          duration: 300,
          easing: "easeOutQuint",
          opacity: 0,
          scale: 0
        });
        bttnBack.style.pointerEvents = "none";

        particles.integrate({
          duration: 500,
          easing: "easeOutSine"
        });
        buttonVisible = !buttonVisible;
      }
    });
  });
}
